using System;
using System.Text;
using System.Windows.Forms;

using FreeFlow.Client;

namespace FreeFlow.WinFormsControls
{
	/// <summary>
	/// A list control.
	/// </summary>
	public class ListControl : ListBox, IFillable, IRefillable
	{
    /// <summary>
    /// Creates a new <see cref="ListControl"/> instance.
    /// </summary>
		public ListControl()
		{
    }

    #region IFillable Members

    /// <summary>
    /// Renders the list with static layout information using the specified field.
    /// </summary>
    /// <param name="field">Field.</param>
    public void Render(FreeFlow.Client.Field field)
    {
      SelectionMode = SelectionMode.MultiSimple;
    }

    /// <summary>
    /// Fills the list with values from the specified field.
    /// </summary>
    /// <param name="field">Field.</param>
    public void Fill(FreeFlow.Client.Field field)
    {
      ListField listField = (ListField)field;
      Items.Clear();
      for (int optionLoop = 0; optionLoop < listField.OptionCount; optionLoop++)
      {
        Items.Add(listField.Option(optionLoop));
      }
            
      // selected items
      for (int optionLoop = 0; optionLoop < listField.SelectedCount; optionLoop++)
      {
        // add if not in the list
        string item = listField.Selected(optionLoop);
        int indexOf = Items.IndexOf(item);
        if (indexOf == -1)
          indexOf = Items.Add(item);
        SetSelected(indexOf, true);
      }
      selectedItems = GetSelectedItems();
    }

    /// <summary>
    /// Fills the field from the control.
    /// </summary>
    /// <param name="field">Field.</param>
    public void FillField(Field field)
    {
      if (field != null)
      {
        StringBuilder builder = new StringBuilder();
        foreach (object item in SelectedItems)
        {
          if (builder.Length > 0)
            builder.Append(",");
          builder.Append(item.ToString());
        }
        field.Value = GetSelectedItems();
      }
    }

    private string GetSelectedItems()
    {
      StringBuilder builder = new StringBuilder();
      foreach (object item in SelectedItems)
      {
        if (builder.Length > 0)
          builder.Append(",");
        builder.Append(item.ToString());
      }
      return builder.ToString();
    }

    #endregion
    #region IRefillable Members

    /// <summary>
    /// Event triggered when a refill should occur
    /// </summary>
    public event System.EventHandler Refill;

    private string selectedItems;
    /// <summary>
    /// Triggers a refill.
    /// </summary>
    /// <param name="e">E.</param>
    protected override void OnLeave(EventArgs e)
    {
      base.OnLeave(e);
      if (GetSelectedItems() != selectedItems)
        if (Refill != null)
          Refill(this, e);
    }

    #endregion
  }
}
